home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 5689 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.5 KB  |  51 lines

  1. Newsgroups: comp.lang.c
  2. Path: news.sprintlink.net!news1!news
  3. From: rclark@iquest.net (Robert B. Clark)
  4. Subject: Re: Function wanted to evaluate string
  5. X-Nntp-Posting-Host: ind-004-236-169.iquest.net
  6. Message-ID: <3129dcde.870616@news.iquest.net>
  7. Sender: news@iquest.net (News Admin)
  8. Organization: IQuest Internet, Inc.
  9. X-Newsreader: Forte Agent .99d/16.182
  10. References: <4g20eo$623@coranto.ucs.mun.ca>
  11. Date: Tue, 20 Feb 1996 15:45:08 GMT
  12.  
  13. On 16 Feb 1996 13:22:32 GMT, cdeacon@kelvin.physics.mun.ca (Chris
  14. Deacon) wrote:
  15.  
  16. >I want a function which will evaluate a string of numbers and
  17. >arithmetic operators. That is, whwn I call
  18. >  
  19. >eval_func(2*5)
  20. >
  21. > a value of 10 will be returned.
  22.  
  23. Somewhat facetiously,
  24.  
  25.     int eval_func(int i); return i;
  26.  
  27. will perform the task to the letter of your specification. :-)
  28.  
  29. I assume that what you *meant* is that you want a routine to parse a
  30. mathematical expression submitted as a string;
  31.  
  32.     int eval_func(const char *expr)    /* Ex, expr="2*5-3" */
  33.  
  34. which is a bit more involved and reminds me of an "infinite precision"
  35. calculator program that I had to write back in CS52.
  36.  
  37. Briefly (it's been a while),
  38.  
  39. 1.  Tokenize the string.  Isolate left and right terms and operators
  40.     inner- to outermost.  Think recursion.
  41. 2.  Evaluate/reduce terms
  42. 3.  Apply operators.
  43. 4.  Go back to 1.
  44.  
  45. I'm sure that there are some good references on the subject; perhaps
  46. some of the other participants can provide some additional pointers.
  47. --
  48. Robert B. Clark <rclark@iquest.net>
  49. "Be wary of strong spirits.  It can make you shoot at tax collectors...
  50. and miss." --RAH
  51.